import json
from sqlalchemy.orm import Session
from core.response import resp_500
from core.logger import logger

from app.audit.models.audit_inspection import AuditInspection
from common.notice_tools import NoticeTools
from common.utils import CommonTimeUtils
from setting import config

class AuditInspectionHandler():
    """  AuditInspection Handler
    """
    def __init__(self):
        self.qywx_group_id = config.AUDIT_QYWX_GROUP_ID
        self.notice_tools = NoticeTools()
        


    def get_audit_inspection_search(self, db: Session, page: int, per_page: int, field: str, value: str):
        """
        巡检记录表, 根据表字段-模糊查询, 获取巡检记录
        """
        try:
            field_info = {field: value}
            order_info = {"create_time": "desc"}
            result = AuditInspection.filter_by_field_search(db, page, per_page, field_info, order_info)
            if not result:
                logger.error(f"get audit inspection search, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get audit inspection search by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def get_audit_inspection_match(self, db: Session, page: int, per_page: int, field: str, value: str):
        try:
            result = AuditInspection.filter_by_field_match(db, page, per_page,{field: value})
            if not result:
                logger.warning(f"get audit inspection match failed, result is null => {field}:{value}")
                return False

        except Exception as e:
            message = f"get audit inspection match by {field}:{value} error"
            logger.exception(f"{message} => {e}")
            return resp_500(message)

        return result



    def delete_audit_inspection(self, db: Session, data: dict):
        """
        删除巡检记录
        """
        try:
            audit_inspection_object = AuditInspection.get_object_by_uuid(db, data['uuid'])
            if not audit_inspection_object:
                # 如果不存在， 则异常返回
                logger.error(f"delete audit inspection failed, uuid:{data['uuid']} not exist")
                return False

            # 删除巡检记录
            AuditInspection.delete_object_by_uuid(db, data['uuid'])
        except Exception as e:
            message = f"delete audit inspection error"
            logger.exception(f"{message} data:{data} => {e}")
            return resp_500(message)

        return True



    def inspection_notice(self, data: dict):
        if not data["is_notice"]:
            # 不需要通知，正常返回
            logger.info(f"inspect_name:{data['inspection_name']} not to notice")
            return True
        
        msg = '## 【巡检审计】 From devops' + '\n' \
              + '> 巡检uuid: ' + str(data["uuid"]) + '\n' \
              + '> 巡检用户：' + data["user_name"] + '\n' \
              + '> 巡检名称：' + data["inspection_name"] + '\n' \
              + '> 巡检类型：' + data["inspection_type"] + '\n' \
              + '> 巡检结果：' + data["inspection_result"] + '\n' \
              + '> 巡检时间：' + data["create_time"] + '\n' \
              + '> 巡检详情：' + data["comment"][:300] + '\n' 
              
        # 发送到大群
        result = self.notice_tools.send_wechatbot(self.qywx_group_id, msg)
        if not result:
            logger.error(f"inspection send to wechat bot failed")
            return False

        logger.info(f"inspection send to wechat bot success")
        return True



    def add_audit_inspection(self, db: Session, data: dict):
        """
        增加巡检记录
        """
        try:
            # 添加到数据库
            result = AuditInspection.add(db, data)
            if not result:
                logger.error(f"add audit inspection to database failed")
                return False
            
            # 发送审计巡检到企业微信群
            data["uuid"] = result.uuid
            data["create_time"] = CommonTimeUtils.strftime(result.create_time)
            result = self.inspection_notice(data)
            if not result:
                logger.error(f"inspection notice failed")
                return False
        except Exception as e:
            message = f"add audit inspection error"
            logger.exception(f"{message} data:{data} => {e}")
            return False

        return True







# def send_to_inspection():
#     url = "https://devops.welab-inc.com/ops/api/v1/audit/inspection/"
#     data = {
#         "user_name": "boll.lai",
#         "inspection_name": "devops生产mysql备份",
#         "inspection_type": "oss备份",
#         "inspection_result": "success",
#         "is_notice": True,
#         "comment": "备份仓库:ops、events"
#     }
#     headers = {
#         "Authorization": "xxxx",
#         "Content-Type": "application/json",
#     }
#     try:
#         r = requests.post(url, headers=headers, data=json.dumps(data))
#         if r.status_code != 200:
#             oss_log.error("send to inspection failed")
#             return False
#     except Exception as e:
#         oss_log.error(f"send to inspection error => {e}")
#         return False

#     oss_log.info("send to inspection success")
#     return True

def main():
    # send_to_inspection()
    # from common.database import SessionLocal
    # db = SessionLocal()
    
    # audit_inspection_handler = AuditInspectionHandler()
    # inspection_data = {
    #     "user_name": "boll.lai",
    #     "inspection_name": "devops生产mysql备份",
    #     "inspection_type": "oss备份",
    #     "is_notice": True,
    #     "comment": "备份了xxxxx"
    # }
    # audit_inspection_handler.add_audit_inspection(db, inspection_data)
    # db.close()
    pass

    
if __name__ == "__main__":
    main()
